package com.zone.vehicle.superapp.view.common.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;
import com.zone.lib.download.DownloadConstant;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.lib.download.utils.DownloadUtil;
import com.zone.lib.download.utils.SharedPreferencesUtil;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.common.http.callback.ResultCallBack;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.entity.AppEntity;
import com.zone.sdk.module.appstore.request.AppsDetailRequest;
import com.zone.sdk_api.ApiManager;
import com.zone.vehicle.lib.view.widget.CustomDialog;
import com.zone.vehicle.superapp.bean.AppBean;
import com.zone.vehicle.superapp.model.AppManagerViewModel;
import com.zone.vehicle.superapp.model.SuperAppServiceModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.INPUT_METHOD_SERVICE;
import static com.zone.sdk_api.common.Content.VIN;

public abstract class BaseFragment<T extends HandledFragment> extends HandledFragment{

    protected static final String TAG = BaseFragment.class.getSimpleName();

    private Map<String, T> pages = new LinkedHashMap<>();
    private Context context;
    protected Activity activity;
    private Handler handler;
    private AppManagerViewModel viewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this.getActivity();
        activity = getActivity();
        dialog = new CustomDialog(context);
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(AppManagerViewModel.class);
        initFragmentPages();
    }

    public Map<String, T> getPages() {
        return pages;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public T getPage(int position){
        List<T> list = new ArrayList<>(pages.values());
        return list.get(position);
    }

    public T getPage(String pageName){
        return pages.get(pageName);
    }

    public void addPage(T fragment) {
        pages.put(fragment.getClass().getSimpleName(), fragment);
    }

    @Override
    public boolean onBack() {
        if (ObjectUtils.isNotEmpty(pageList)) {
            return change(pageList.removeLast());
        } else {
            finish();
        }
        return false;
    }

    @Override
    protected void finish() {
        activity.finish();
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver();
    }

    private void registerReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadConstant.APP_STATUS_ACTION);
        filter.addAction(DownloadConstant.ACTION_PRE+AppStatusEnum.DOWNLOAD_PREPARE.CODE);//下载、继续
        filter.addAction(DownloadConstant.ACTION_PRE+AppStatusEnum.DOWNLOAD_PAUSE.CODE);//暂停
        filter.addAction(DownloadConstant.ACTION_PRE+AppStatusEnum.DOWNLOAD_CONTINUE.CODE);//继续
        filter.addAction(DownloadConstant.ACTION_PRE+AppStatusEnum.UNINSTALL_APP_AND_LIGHT.CODE);//卸载apk或light
        filter.addAction(DownloadConstant.ACTION_PRE+AppStatusEnum.UPDATE.CODE);//更新
        requireActivity().registerReceiver(receiver, filter);
    }

    private void unregisterReceiver(){
        requireActivity().unregisterReceiver(receiver);
    }

    static CustomDialog dialog = null;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String actionStr = intent.getAction();
            Log.d(TAG, "broadcast receive action="+actionStr);
            if (null != intent) {
                if (intent.getAction().equals(DownloadConstant.APP_STATUS_ACTION)){
                    //本地状态更新
                    Download download = (Download)intent.getSerializableExtra(DownloadConstant.EXTRA_INTENT_APP_STATUS);
                    if (handler != null) {
                        Message message = new Message();
                        message.what = 1;
                        message.obj = download;
                        handler.sendMessage(message);
                    }
                }else {
                    //云端指令推送
                    AppDetailEntity appEntity = null;
                    int action = -1;
                    Object appEntityObj = intent.getSerializableExtra(DownloadConstant.EXTRA_INTENT_APP_STATUS_APP);
                    if (ObjectUtils.isNotEmpty(appEntityObj)){
                        appEntity = (AppDetailEntity)appEntityObj;
                        action = Integer.parseInt(intent.getAction().replace(DownloadConstant.ACTION_PRE, ""));
                        Log.d(TAG, "cloud action="+action);
//                        if(action == AppStatusEnum.DOWNLOAD_PREPARE.CODE
//                            || action == AppStatusEnum.UNINSTALL_APP_AND_LIGHT.CODE){
//                            showInstallDialog(AppStatusEnum.get(action), appEntity);
//                        }
                        if (action == AppStatusEnum.DOWNLOAD_PREPARE.CODE){
                            download(appEntity);
                        }else if (action == AppStatusEnum.UNINSTALL_APP_AND_LIGHT.CODE){
                            List<AppBean> appBeanList = viewModel.getInstalledApp().getValue();
                            if (ObjectUtils.isNotEmpty(appBeanList)) {
                                for (int i = 0; i < appBeanList.size(); i++) {
                                    AppBean appBean = appBeanList.get(i);
                                    if (appBean.getCode().equals(appEntity.getCode())) {
                                        viewModel.delete(activity, appBean);
                                    }
                                }
                            }
                        }else if (action == AppStatusEnum.DOWNLOAD_PAUSE.CODE){
                            viewModel.downLoadApp(activity, AppStatusEnum.DOWNLOAD_PAUSE, appEntity);
                        }else if (action == AppStatusEnum.DOWNLOAD_CONTINUE.CODE){
                            viewModel.downLoadApp(activity, AppStatusEnum.DOWNLOAD_PREPARE, appEntity);
                        }else if (action == AppStatusEnum.UPDATE.CODE){
                            Log.d(TAG, "cloud update action="+action);
//                            viewModel.updateApk(activity, AppStatusEnum.DOWNLOAD_PREPARE, appEntity);
                            SuperAppServiceModel.updateApk(activity, appEntity.getCode());
//                            AppBean appBean = new AppBean();
//                            appBean.build(appEntity);
//                            AppsUpdateListRequest request = new AppsUpdateListRequest();
//                            request.setAppCode(appEntity.getCode());
//                            ApiManager.getInstance().updateList(request, new ResultCallBack<Result<List<AppUpdateEntity>>>() {
//                                @Override
//                                public void onSuccess(Result<List<AppUpdateEntity>> listResult) {
//                                    appBean.setUpdateEntity(listResult.getData().get(0));
//
//                                }
//
//                                @Override
//                                public void onError(String errorCode, String message) {
//                                }
//
//                                @Override
//                                public void onComplete() {
//                                }
//                            });
                        }
                    }
                }
            }
        }
    };

    private void showInstallDialog(AppStatusEnum appStatusEnum, AppDetailEntity appEntity){
        Log.d(TAG, "showInstallDialog="+ JSON.toJSONString(appEntity));
        List<AppBean> appBeanList = viewModel.getInstalledApp().getValue();
        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
        if (!dialog.isShowing()) {
            String action = "";
            if (appStatusEnum == AppStatusEnum.DOWNLOAD_PREPARE){
                action = "安装";
            }else if (appStatusEnum == AppStatusEnum.DOWNLOAD_PAUSE){
                action = "暂停";
            }else if (appStatusEnum == AppStatusEnum.DOWNLOAD_CONTINUE){
                action = "继续安装";
            }else if (appStatusEnum == AppStatusEnum.UNINSTALL_APP_AND_LIGHT){
                if (ObjectUtils.isNotEmpty(download)){
                    if (download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE){
                        action = "卸载";
                    }else {
                        action = "删除";
                    }
                }else {
                    return;
                }
            }else if (appStatusEnum == AppStatusEnum.UPDATE){
                action = "更新";
            }
            dialog.setTitle("远程请求"+action+" " + appEntity.getName());
            dialog.setSubTitle("是否同意");
            dialog.setPositive("同意");
            dialog.setNegtive("不同意");
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    dialog.cancel();
                }
            });
            String finalAction = action;
            dialog.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
                @Override
                public void onPositiveClick() {
                    Toast.makeText(context, "开始"+finalAction, Toast.LENGTH_SHORT).show();
                    if (appStatusEnum == AppStatusEnum.DOWNLOAD_PREPARE){
                        download(appEntity);
                    }else if (appStatusEnum == AppStatusEnum.UNINSTALL_APP_AND_LIGHT){
                        for (int i = 0; i < appBeanList.size(); i++) {
                            AppBean appBean = appBeanList.get(i);
                            if (appBean.getCode().equals(appEntity.getCode())){
                                viewModel.delete(activity, appBean);
                            }
                        }
                    }
                    dialog.cancel();
                }

                @Override
                public void onNegtiveClick() {
                    Toast.makeText(context, "取消"+ finalAction, Toast.LENGTH_SHORT).show();
                    dialog.cancel();
                }
            });
            try {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                    Toast.makeText(activity, "云端指令", Toast.LENGTH_LONG).show();
                        dialog.show();
                    }
                });
            }catch (Exception e){
                Log.e(TAG, e.toString());
            }
        }
    }

    private void download(AppDetailEntity appEntity) {
        Log.d(TAG, "download="+ JSON.toJSONString(appEntity));
        AppsDetailRequest request = new AppsDetailRequest();
        request.setSpuId(appEntity.getCode());
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        ApiManager.getInstance().appsDetail(request, new ResultCallBack<Result<AppDetailEntity>>() {
            @Override
            public void onSuccess(Result<AppDetailEntity> result) {
                if (result.getResultCode().equals("200")) {
                        AppDetailEntity appEntity = result.getData();
                    if (appEntity != null && appEntity.isApp()){
                        String userId = SharedPreferencesUtil.getInstance(context).getUserId(context);
                        DownloadUtil.downLoad(context, AppStatusEnum.DOWNLOAD_PREPARE.CODE, userId, appEntity);
                    }
                }
            }

            @Override
            public void onError(String errorCode, String message) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    public boolean checkPwd(String password){
//        String check = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_]{8,20}$";
        String checkNumber = "[0-9]+$";
        Pattern regex = Pattern.compile(checkNumber);
        Matcher matcher = regex.matcher(password);
        if(matcher.matches()|| password.length() < 8 || password.length() > 20){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, "密码输入错误，8-20个字符，不可以是纯数字", Toast.LENGTH_LONG).show();
                }
            });
            return false;
        }
        return true;
    }

    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public void showInput(final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) requireActivity().getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) requireActivity().getSystemService(INPUT_METHOD_SERVICE);
        View v = requireActivity().getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    protected void hideInput(View view) {
        InputMethodManager imm = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }

    public void runOnUiThread(Runnable runnable){
        requireActivity().runOnUiThread(runnable);
    }

    @Override
    public void showErrorPage(int type){

    }
}
